package com.usian.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.model.admin.pojos.AdUser;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.user.dtos.LoginDto;
import com.usian.model.user.pojos.ApUser;
import com.usian.user.mapper.ApUserMapper;
import com.usian.user.service.ApUserService;
import com.usian.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {


    @Override
    public ResponseResult login(LoginDto dto) {
        //1:校验参数
        if (StringUtils.isEmpty(dto.getPhone()) || StringUtils.isEmpty(dto.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE, "用户名或密码不能为空");
        }

        //2：数据库查用户是否合法
        Wrapper wrapper =new QueryWrapper<ApUser>();
        ((QueryWrapper) wrapper).eq("phone",dto.getPhone());

        if(StringUtils.isBlank(dto.getPhone()) && StringUtils.isBlank(dto.getPassword())){
            //设备登录
            ApUser apUser =new ApUser();
            Map<String, Object> map =new HashMap<>();
            apUser.setPassword("");
            apUser.setSalt("");
            map.put("token", AppJwtUtil.getToken(0L));  //生成token 包含用户的id
            map.put("user",apUser);
            //4:把token 返回前端
            return ResponseResult.okResult(map);

        }else{
            List<ApUser> userList = this.list(wrapper);  //查询出用户信息
            if(userList !=null && userList.size()==1){
                ApUser apUser = userList.get(0);

                //根据查询的用户密码 +库中的盐值 生成一个新的加密密码串，比较
                String salt = apUser.getSalt();
                String pwdSalt = dto.getPassword()+salt;

                String newPwd = DigestUtils.md5DigestAsHex(pwdSalt.getBytes());
                if(newPwd.equals(apUser.getPassword())){
                    //用户密码是输入对的    //3:生成token jwt
                    Map<String, Object> map =new HashMap<>();
                    apUser.setPassword("");
                    apUser.setSalt("");
                    map.put("token", AppJwtUtil.getToken(apUser.getId().longValue()));  //生成token 包含用户的id
                    map.put("user",apUser);

                    //4:把token 返回前端
                    return ResponseResult.okResult(map);
                }
            }
        }

        return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
    }
}
